/*************************************************************************
	> File Name: nanosleep.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Tue 01 Jul 2014 08:05:24 PM CST
 ************************************************************************/
#define _POSIX_C_SOURCE 199309
#include"time.h"

void dealing(int sig)
{
    if(sig==SIGALRM)
    {
        printf("Cought signal\t nanosleep completed\n");
        _exit(0);
    }
    return;
}

int main(int argc,char *argv[])
{
    if(argc<3)
    {
        printf("%s time\n",argv[0]);
        _exit(0);
    }

    struct timespec req; // declare request time
    struct timespec rem; // declare remain time
    struct sigaction act;
    int s;

    sigemptyset(&act.sa_mask);
    sigaddset(&act.sa_mask,SIGINT);
    act.sa_flags=0;
    act.sa_handler=dealing;

    req.tv_sec=atol(argv[1]);
    req.tv_nsec=atol(argv[2]);

    if(sigaction(SIGINT,&act,NULL)==-1)
    {
        perror("sigaction_sigint");
        _exit(errno);
    }

    if(sigaction(SIGALRM,&act,NULL)==-1)
    {
        perror("sigaction_sigalrm");
        _exit(errno);
    }

    for(;;)
    {
        s=nanosleep(&req,&rem); // use SIGINT to interrupt nanosleep\
        then restore it at line 62

        if(s==0)
            raise(SIGALRM);

        printf("time remain: %2ld.%09ld\n",(long)rem.tv_sec,rem.tv_nsec);
        req=rem;  // restore requst time
    }
}
